<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="付方信息" v-bind="validateInfos.payName">
            <a-input :value="formData.payName + '--' + formData.payAccount + formData.payDmanbr" placeholder="请输入付方信息" disabled></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="付方公司" v-bind="validateInfos.payDmanam">
            <a-input v-model:value="formData.payDmanam" placeholder="请输入付方公司" disabled></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收方信息" v-bind="validateInfos.crtAccount">
            <a-select v-model:value="crtInfo" @change="handleCrtAccountChange" placeholder="请选择收方信息">
              <template #suffixIcon>
                <Icon icon="ant-design:credit-card-outlined" />
              </template>
              <template v-for="item in crtAccountList" :key="item.value">
                <a-select-option :value="item.label + '-' + item.value">{{ item.label + '--' + item.value }}</a-select-option>
              </template>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开户银行" v-bind="validateInfos.bankName">
            <a-input v-model:value="formData.bankName" placeholder="请输入开户银行，例如：招商银行" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开户支行" v-bind="validateInfos.bankBranch">
            <a-input v-model:value="formData.bankBranch" placeholder="请输入开户支行" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
<!--        <a-col :span="24">
          <a-form-item label="开户地" v-bind="validateInfos.bankAddress">
	          <j-area-linkage @change="areaChange" v-model:value="formData.bankAddress" placeholder="请输入开户地" :disabled="disabled" />
          </a-form-item>
        </a-col>-->
        <a-col :span="12">
          <a-form-item label="账户余额" :label-col="{ span: 10 }" :wrapper-col="{ span: 12 }">
            <a-input :value="parseFloat(moneyInfo.accountBalance).toFixed(2)" suffix="元" disabled/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="可退款金额" :label-col="{ span: 8 }" :wrapper-col="{ span: 10 }">
            <a-input :value="parseFloat(moneyInfo.refundableAmount).toFixed(2)" suffix="元" disabled style="width: 80%;"/>
            <a-tooltip title="可退款金额 = 充值总额 - 开票金额（开票中+开票成功） - 退款金额（退款中+退款成功）">
              <Icon icon="ant-design:question-circle-outlined" style="margin-left: 5px;"/>
            </a-tooltip>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="退款金额" v-bind="validateInfos.money" :label-col="{ span: 10 }" :wrapper-col="{ span: 12 }">
            <a-input-group compact>
              <a-input v-model:value="formData.money" placeholder="退款金额" style="width: calc(100% - 68px)" @change="moneyChange"
                        @keyup="checkInput" @blur="checkNum" />
              <a-button type="primary" @click="selectAll">全部</a-button>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="实际到账金额" :label-col="{ span: 8 }" :wrapper-col="{ span: 10 }"
                       :help="'手续费：'+parseFloat(formData.serviceFee).toFixed(2)">
            <a-input :value="parseFloat(moneyInfo.receiptAmount).toFixed(2)" suffix="元" disabled/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="手机验证码" v-bind="validateInfos.captcha">
            <CountdownInput class="fix-auto-fill" v-model:value="formData.captcha" placeholder="请输入手机验证码" :sendCodeApi="sendCodeApi" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-checkbox style="margin-left: 156px;margin-top: 20px;" v-model:checked="checked">
            请准确填写收款信息，若您填写的信息错误，造成的后果由填写人承担。
          </a-checkbox>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {checkInput, checkNum} from '/@/utils/common/compUtils.ts';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, queryBusinessBankInfo } from "../CaishuiRefundRecord.api";
  import { Form } from 'ant-design-vue';
  import { CountdownInput } from "/@/components/CountDown";
  import { getCaptcha } from "/@/api/sys/user";
  import { SmsEnum } from "/@/views/sys/login/useLogin";
  import { useUserStore } from "/@/store/modules/user";
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    companyId: '',   
    businessId: '',   
    tenantId: undefined,
    yurRef: '',
    payAccount: '',   
    payName: '',   
    payDmanbr: '',   
    payDmanam: '',   
    crtAccount: '',   
    crtName: '',   
    bankName: '',   
    bankBranch: '',   
    bankInterbankNumber: '',   
    bankAddress: '',   
    money: undefined,
    serviceFee: 0.00,
    remark: '',   
    reqSts: '',   
    rtnFlg: '',   
    failReason: '',   
    status: undefined,
    rejectReason: '',   
    checkTime: '',   
    finishTime: '',
    captcha: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    crtAccount: [{ required: true, message: '请选择收方信息!'},],
    bankName: [{ required: true, message: '请输入开户银行!'},],
    bankBranch: [{ required: true, message: '请输入开户支行!'},],
    // bankAddress: [{ required: true, message: '请选择开户地!'},],
    money: [{ required: true, message: '请输入退款金额!'},],
    captcha: [{ required: true, message: '请输入手机验证码!'},],
  };
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: true });
   // 表单禁用
   const disabled = computed(()=>{
      let bool = false;
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          bool = false;
        }else{
          bool =  true;
        }
      }
      bool = props.formDisabled;
      //清除表单验证
      clearValidate();
      return bool;
   });
  const crtAccountList = ref([]);//收方信息列表
  const crtInfo = ref("");//收方默认选中
  const checked = ref<boolean>(false);
  const moneyInfo = ref<any>({
    accountBalance: 0.00,
    refundableAmount: 0.00,
    receiptAmount: 0.00,
  });//账户余额、可退款金额
  const userStore = useUserStore();

  /**
   * 选择收方信息事件
   * @param e
   */
  function handleCrtAccountChange(e){
    formData.crtAccount = e.split("-")[1];
    formData.crtName = e.split("-")[0];
  }

  /**
   * 选择全部退款金额事件
   */
  function selectAll(){
    const money = parseFloat(moneyInfo.value.refundableAmount);
    formData.money = money.toFixed(2);
    getMoney(money);
  }

  /**
   * 退款金额改变事件
   */
  function moneyChange(e){
    const value = parseFloat(e.target.value);
    getMoney(value);
  }

  /**
   * 计算金额
   * @param value
   */
  async function getMoney(value){
    const money = parseFloat(moneyInfo.value.refundableAmount);
    if (Number.isNaN(value)) {
      moneyInfo.value.receiptAmount = 0.00;
      return;
    }
    if (value > money){
      formData.money = "";
      formData.serviceFee = 0.00;
      moneyInfo.value.receiptAmount = 0.00;
      createMessage.warning("最高可退款金额："+money.toFixed(2));
    }else if (value <= 5){
      formData.money = "";
      formData.serviceFee = 0.00;
      moneyInfo.value.receiptAmount = 0.00;
      createMessage.warning("退款金额不能小于等于5元！");
    }else if (value >= 1000000){
      formData.money = "";
      formData.serviceFee = 0.00;
      moneyInfo.value.receiptAmount = 0.00;
      createMessage.warning("退款金额不能大于等于100万元！");
    }else {
      let fee = await getFee(value);
      formData.serviceFee = fee;
      moneyInfo.value.receiptAmount = parseFloat(value-fee).toFixed(2);
    }
  }

  /**
   * 计算手续费
   * @param value
   */
  async function getFee(value){
    let fee = 0.00;
    if (value <= 10000) {
      fee = 5.00;
    }else if (value <= 100000) {
      fee = 10.00;
    }else if (value <= 500000) {
      fee = 15.00;
    }else if (value <= 1000000) {
      fee = 20.00;
    }
    return fee;
  }

  //倒计时执行前的函数
  function sendCodeApi() {
    let mobile = userStore.getUserInfo.username;
    if (!mobile) {
      createMessage.warning("手机号码不存在!");
      return;
    }
    return getCaptcha({ mobile: mobile, smsmode: SmsEnum.FORGET_PASSWORD, userType: 2,remarks: '申请退款手机号验证' });
  }

  /**
   * 新增
   */
  async function add(record) {
    formData.businessId = record.businessId;
    formData.companyId = record.serviceCompanyId;
    formData.tenantId = record.tenantId;
    formData.payAccount = record.mainAccount;
    formData.payName = record.name;
    formData.payDmanbr = record.subAccountId;
    formData.payDmanam = record.accountName;
    //查询相关信息
    await queryBusinessBankInfo(record).then((res) => {
      if (res.success) {
        crtAccountList.value = res.result.crtAccountList;
        if (crtAccountList.value && crtAccountList.value.length > 0){
          crtInfo.value = crtAccountList.value[0].label + '-' + crtAccountList.value[0].value;
        }
        moneyInfo.value.accountBalance = res.result.accountBalance;
        moneyInfo.value.refundableAmount = res.result.refundableAmount;
        moneyInfo.value.receiptAmount = 0.00;
        formData.crtAccount = crtAccountList.value[0].value;
        formData.crtName = crtAccountList.value[0].label;
      } else {
        createMessage.warning(res.message);
      }
    })
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    if (!checked.value) {
      createMessage.warning("请先同意退款承诺！");
      return;
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //数据格式化
    let model = formData;
    if (model.id) {//编辑
       isUpdate.value = true;
       model.updateBy = "";
       model.updateTime = "";
    }else {//新增
       model.createBy = "";
       model.createTime = "";
       model.sysOrgCode = "";
       model.updateBy = "";
       model.updateTime = "";
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    // console.log("=====表单提交数据======:",model);
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
